#!/usr/bin/env python2
# ----------------------------------------------------------------------------
# Ugh. The bit that got done last, due to the problem of just having any idea
# of how packet collection should be done.
#
# This moves queue/outgoing packets to the 'live' KISS_OUT directory, where
# they're expected to be transmitted (and removed) somewhat promptly,
# although the TNC has final say on that.
#
# TODO: make this more cron friendly

import time, os, sys
import site_config as cfg

# stdout's progress information, otherwise only to a logfile
doverbose = True
doimm = False

while len(sys.argv) > 1:
   if sys.argv[1] == "quiet":
      doverbose = False
   if sys.argv[1] == "immediate":
      doimm = True
   sys.argv = sys.argv[1:]

#
#
#

def queueout_filelist():
   ret = []

   for root, dirs, files in os.walk (cfg.QUEUE_OUT):
      for name in files:
         f = os.path.join (root, name)
         ret.append (f)
   return ret

#
# find the unix time for the previous midnight to reference 'minutes' against
#

t = time.time()
(year, mon, mday, hour, t_min, sec, wday, yday, isdst) = time.localtime()
mid = time.mktime((year, mon, mday, 0, 0, 0, wday, yday, -1))

#
#
#

(lastdirtime, looped, files) = (0, False, [])

while True:
   if looped and doimm:
      break
   looped = True

   if not doimm:
      # Wait for the next transmission slot
      to = (time.time() - mid) % cfg.LIMITS[cfg.RADIOMODE]["TXCLOCK"]
      w = cfg.LIMITS[cfg.RADIOMODE]["TXSLOT"] - to
      if w < 0:
         w += cfg.LIMITS[cfg.RADIOMODE]["TXCLOCK"]
      time.sleep (w)

      if doverbose:
         print "Time:", time.ctime()

   if os.path.isfile (os.path.join (cfg.QRPBBBHOME, "Pause")):
      print "PAUSED"
      continue

   # Refresh directory if files[] empty or directory has been modified by a
   # new file. (Would make little difference just scanning every time. 21st
   # Century..)

   dirtime = os.path.getmtime (cfg.QUEUE_OUT)
   if len(files) < 1 or dirtime != lastdirtime:
      # todo: log the rescanning notice
      if doverbose:
         print "Rescanning queue_out.",
      lastdirtime = dirtime
      files = sorted (queueout_filelist())
      print len(queueout_filelist()),"packets remaining."

   if len(files) < 1:
      continue

   # Move from QRPBBB's queue to the packet transmission spool
   # would kissutil handle multiple packets in the one file?

   for i in range (min (cfg.LIMITS[cfg.RADIOMODE]["PCKATTIME"], len(files))):
      f = files[i]
      name = os.path.basename (f)

      if doverbose:
         print "Moving to transmission queue:", name

      if os.path.isfile (os.path.join(cfg.QRPBBBHOME, "NoTX")):
         print "    NoTX:",
         foo = open (f, 'r')
         print foo.readline()
         foo.close()
         os.remove (f)
         continue
      else:
         os.rename (f, os.path.join(cfg.KISS_OUT, name))

#
# ----------------------------------------------------------------------------
#
